package com.atguigu.tingshu.album.config;

import jakarta.annotation.PostConstruct;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/***
 * 专辑微服务发送数据同步消息的可靠性投递配置
 * 实现RabbitTemplate.ReturnsCallback接口 用于处理消息没有抵达队列的情况
 */
@Component
@Log4j2
@AllArgsConstructor
public class AlbumAndSearchReturnCallBackConfig implements RabbitTemplate.ReturnsCallback {

    private RabbitTemplate rabbitTemplate;

    /**
     * 触发一次的配置方法
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setReturnsCallback(this::returnedMessage);
    }

    /**
     * 可靠性投递触发时候的回调方法: 消息没有抵达队列触发 记录到日志
     *
     * @param returnedMessage 没有抵达队列的消息
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.error("上下架消息发送失败,失败的专辑id为:"
                + new String(returnedMessage.getMessage().getBody())
                + ",交换机为:" + returnedMessage.getExchange()
                + ",routingKey为:" + returnedMessage.getRoutingKey());
    }
}
